package com.snts.synchronization.loader;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.snts.synchronization.ChangeManager;
import com.snts.synchronization.core.Change;
import com.snts.synchronization.core.SyncTable;
import com.snts.synchronization.core.Synchronization;
import com.snts.synchronization.core.UUID;

public class ChangeManagerImpl implements ChangeManager {

	private static final Log log = LogFactory.getLog(ChangeManagerImpl.class);

	private Synchronization synchronization;

	public void setSynchronization(Synchronization synchronization) {
		this.synchronization = synchronization;
	}

	@Override
	public List<Change> getChanges(Connection conn, UUID restaurantId) throws SQLException {
		List<Change> changes = new ArrayList<Change>();
		for (SyncTable syncTable : synchronization.getTables()) {
			try {
				changes.addAll(syncTable.getTableLog().getChanges(conn, restaurantId));
			} catch (SQLException sqle) {
				log.error("Got exception (" + sqle.toString() + ")");
				log.error("error loading changes for table " + syncTable.getSchema() + "." + syncTable.getName());
			}
		}
		Collections.sort(changes, new Comparator<Change>() {

			@Override
			public int compare(Change o1, Change o2) {
				return (int) (o1.getTime().getGMTTime() - o2.getTime().getGMTTime());
			}

		});
		return changes;
	}

	@Override
	public void deleteChanges(Connection conn, List<Change> changes) throws SQLException{
		for(Change change : changes){
			change.getTable().getTableLog().deleteChange(conn, change);
		}
	}

}
